package com.xbongbong.workflow.service.strategy.data.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.TaskTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ProductionOrderProductEntity;
import com.xbongbong.saas.domain.entity.ProductionOrderUserEntity;
import com.xbongbong.saas.domain.entity.ext.ProductionOrderEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.ProductionOrderModel;
import com.xbongbong.saas.model.ProductionOrderProductModel;
import com.xbongbong.saas.model.ProductionOrderUserModel;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy;
import com.xbongbong.workflow.service.strategy.data.WorkflowDataProcessStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 *
 * @author 魏荣杰
 *
 */
@Service
public class WorkflowProductionOrderStrategy extends AbstractWorkflowDataStrategy implements WorkflowDataProcessStrategy {

    private static Logger log = LoggerFactory.getLogger(WorkflowProductionOrderStrategy.class);

    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private ProductionOrderModel productionOrderModel;
    @Resource
    private ProductionOrderUserModel productionOrderUserModel;
    @Resource
    private ProductionOrderProductModel productionOrderProductModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;

    @Override
    public List<Integer> type() {
        return Collections.singletonList(XbbRefTypeEnum.PRODUCTION_ORDER.getCode());
    }

    @Override
    public void save(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        // api
        apiHook(workflowTransferPOJO);
        addLinkDataDynamic(workflowTransferPOJO);
        // log
        afterSaveLog(workflowTransferPOJO);
    }

    @Override
    public void update(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        // api
        apiHook(workflowTransferPOJO);
        // log
        afterUpdateLog(workflowTransferPOJO);
    }

    @Override
    public void updateBack(Long taskId, WorkflowTransferPOJO workflowTransferPOJO) throws XbbException{
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Long backupDataId = workflowTransferPOJO.getBackupDataId();
            Long dataId = workflowTransferPOJO.getData().getId();
            WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(backupDataId, corpid);
            if (Objects.nonNull(workflowBackupDataEntity)) {
                JSONObject data = workflowBackupDataEntity.getData();

                replenishAttrForBackupData(workflowTransferPOJO.getData().getData(), data);

                ProductionOrderEntityExt productionOrderEntityExt = new ProductionOrderEntityExt();
                productionOrderEntityExt.setId(dataId);
                productionOrderEntityExt.setCorpid(corpid);
                productionOrderEntityExt.setData(data);
                productionOrderEntityExt.setSerialNo(data.getString(FieldTypeEnum.SERIALNO.getAlias()));
                // 获取负责人
                productionOrderEntityExt.setOwnerId(getOwnerId(data));
                productionOrderEntityExt.setDepartmentId(data.getLong(FieldTypeEnum.DEPARTMENTID.getAlias()));
                List<ProductionOrderProductEntity> list = JSON.parseArray(data.getString(StringConstant.PRODUCT), ProductionOrderProductEntity.class);
                List<ProductionOrderUserEntity> contractUserList = JSON.parseArray(data.getString(StringConstant.USER_TEAM), ProductionOrderUserEntity.class);

                FormDataUtil.removeSystemData(data);
                data.remove(StringConstant.USER_TEAM);
                data.remove(StringConstant.PRODUCT);
                if (Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.UPDATE.getType())) {
                    productionOrderEntityExt.setFlowStatus(FlowStatusEnum.PASS.getType());
                }
                productionOrderModel.update(productionOrderEntityExt);
                // 回退被删掉的子表单
                updateBackSubForm(productionOrderEntityExt, corpid, IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER_SUB);
                //回退被删掉的富文本
                updateBackRichText(taskId, workflowTransferPOJO);
                saveUserTeam(contractUserList, corpid, productionOrderEntityExt.getId());
                saveProduct(list, corpid, productionOrderEntityExt.getId());
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowProductionOrderStrategy.updateBack error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public void approvalFailed(Long taskId, WorkflowTransferPOJO workflowTransferPOJO, Integer taskType) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Data workflowData = workflowTransferPOJO.getData();
            Long dataId = workflowData.getId();
            Long formId = workflowData.getFormId();
            Integer businessType = workflowData.getBusinessType();
            Integer saasMark = workflowData.getSaasMark();
            ProductionOrderEntityExt productionOrderEntityExt = new ProductionOrderEntityExt();
            productionOrderEntityExt.setId(dataId);
            if (Objects.equals(TaskTypeEnum.REVOKE.getType(), taskType)) {
                productionOrderEntityExt.setFlowStatus(FlowStatusEnum.REVOKE.getType());
            } else {
                productionOrderEntityExt.setFlowStatus(FlowStatusEnum.REJECT.getType());
            }
            productionOrderEntityExt.setCorpid(corpid);
            productionOrderEntityExt.setUpdateTime(DateTimeUtil.getInt());
            productionOrderModel.update(productionOrderEntityExt);
            // 子表单
            DelEnum del = DelEnum.APPROVE_FAILED;

            paasFormSubDataModel.deleteBatchByDataId(Collections.singletonList(dataId), corpid, IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER_SUB, del);
            //富文本
            deleteFormRichText(dataId, corpid, formId, businessType, saasMark, DelEnum.NORMAL);

            // 关联产品
            List<ProductionOrderProductEntity> productList = productionOrderProductModel.getProductsById(dataId, corpid, null);
            if (CollectionsUtil.isNotEmpty(productList)) {
                List<Long> idIn = new ArrayList<>();
                productList.forEach(item->idIn.add(item.getId()));
                productionOrderProductModel.deleteBatch(idIn, corpid, del.getDel());
            }
            // 团队
            List<ProductionOrderUserEntity> contractUserList = productionOrderUserModel.getProductionOrderUserListByProductionOrderId(corpid, dataId);
            if (CollectionsUtil.isNotEmpty(contractUserList)) {
                productionOrderUserModel.deleteBatchUser(contractUserList, corpid, del.getDel());
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowProductionOrderStrategy.updateBack error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    private void saveProduct(List<ProductionOrderProductEntity> list, String corpid, Long dataId) throws XbbException {
        try {
            List<ProductionOrderProductEntity> productList = productionOrderProductModel.getProductsById(dataId, corpid, null);
            List<Long> deleteIdIn = new ArrayList<>();

            // 遍历备份表中的产品
            List<Long> backupProductId = new ArrayList<>();
            list.forEach(item->backupProductId.add(item.getId()));
            // 遍历数据库中的产品


            // 移除掉备份表中的产品
            productList.forEach(item->{
               if (!backupProductId.contains(item.getId())) {
                   deleteIdIn.add(item.getId());
               }
            });

            if (CollectionsUtil.isNotEmpty(deleteIdIn)) {
                productionOrderProductModel.deleteBatch(deleteIdIn, corpid, DelEnum.DELETE.getDel());
            }
            if (CollectionsUtil.isNotEmpty(list)) {
                productionOrderProductModel.updateMulti(list, corpid);
            }


        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowContractStrategy.saveProduct error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 保存团队
     * @param list
     * @param corpid
     * @param dataId
     * @throws XbbException
     */
    private void saveUserTeam(List<ProductionOrderUserEntity> list, String corpid, Long dataId) throws XbbException {

        try {
            List<ProductionOrderUserEntity> contractUserList = productionOrderUserModel.getProductionOrderUserListByProductionOrderId(corpid, dataId);
            List<Long> idList = new ArrayList<>();
            list.forEach(item->idList.add(item.getId()));


            contractUserList.removeIf(item->idList.contains(item.getId()));
            if (CollectionsUtil.isNotEmpty(contractUserList)) {
                productionOrderUserModel.deleteBatchUser(contractUserList, corpid, DelEnum.DELETE.getDel());
            }
            if (CollectionsUtil.isNotEmpty(list)) {
                productionOrderUserModel.updateBatch(list, corpid);
            }


        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowContractStrategy.saveUserTeam error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
}
